<!-- 创建会员基础资料 -->
<template>
  <div>
    <!-- :rules="dataRule" -->
    <el-form :model="dataForm"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmit()"
             label-width="100px"
             label-position="top"
             size="small"
             :inline="false">
      <el-row :gutter="20">
        <el-col :span="14">
          <el-row :gutter="10">
            <el-col :span="12">

              <!-- show-word-limit -->
              <el-form-item label="身份证号"
                            prop="idcard">
                <el-input v-model="dataForm.idcard"
                          placeholder="身份证号"
                          maxlength="18"
                          :disabled="idcardDisabled"
                          v-fo></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话"
                            prop="telphone">
                <!-- show-word-limit -->
                <el-input v-model="dataForm.telphone"
                          placeholder="联系电话"
                          maxlength="11"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="姓名"
                            prop="name">
                <el-input v-model="dataForm.name"
                          placeholder="姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-form-item label="年龄"
                                prop="age">
                    <el-input v-model="dataForm.age"
                              placeholder="年龄"
                              maxlength="3"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="性别"
                                prop="sex">
                    <template>
                      <el-radio-group v-model="dataForm.sex">
                        <el-radio-button :label="1">男</el-radio-button>
                        <el-radio-button :label="0">女</el-radio-button>
                      </el-radio-group>
                    </template>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="职业"
                            prop="job">
                <el-input v-model="dataForm.job"
                          placeholder="职业"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="籍贯"
                                prop="hometownVal">
                    <!--<el-select v-model="dataForm.hometown">
                      <el-option v-for="item in selectOps.hometown"
                                 :key="item.id"
                                 :label="item.name"
                                 :value="item.id"></el-option>
                    </el-select>-->
                    <el-input v-model="dataForm.hometownVal"
                              placeholder="输入地名、祖籍"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出生日期"
                                prop="birthday">
                    <el-date-picker v-model="dataForm.birthday"
                                    type="date"
                                    placeholder="选择日期"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-col>
          </el-row>
        </el-col>
        <el-col :span="10">
          <el-form-item label="头像"
                        prop="avatar"
                        border>
            <!-- <single-upload v-on:setAvatarUrl="setAvatarUrl"></single-upload> -->
            <single-upload v-model="dataForm.avatar"></single-upload>
            <!-- <single-upload></single-upload> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="14">
          <el-col :span="12">
            <el-form-item label="兴趣爱好"
                          prop="hobby">
              <el-input v-model="dataForm.hobby"
                        placeholder="兴趣爱好"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区"
                          prop="districtArr">
              <el-cascader id="el-cascader"
                           :options="districts"
                           :props="districtProps"
                           v-model="dataForm.districtArr"
                           placeholder="请选择地区"
                           @change="handleChange"
                           clearable
                           style="width: 260px"></el-cascader>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="10">
          <el-form-item label="详细地址"
                        prop="address">
            <el-input v-model="dataForm.address"
                      placeholder="详细地址"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="7">
          <el-form-item label="健康状况"
                        prop="health">
            <el-input v-model="dataForm.health"
                      placeholder="健康状况"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="学历"
                        prop="education">
            <el-select v-model="dataForm.education">
              <el-option v-for="item in selectOps.education"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="有无保险"
                        prop="insurance">
            <el-select v-model="dataForm.insurance">
              <el-option v-for="item in selectOps.insurance"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="婚姻状况"
                        prop="marriage">
            <el-select v-model="dataForm.marriage">
              <el-option v-for="item in selectOps.marriage"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="居住情况"
                        prop="reside">
            <el-select v-model="dataForm.reside">
              <el-option v-for="item in selectOps.reside"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary"
                       @click="dataFormSubmit">提交基本资料</el-button>
            <el-button type="primary"
                       @click="setStepVal">下一步，办理会员卡</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog title="基础资料数据"
               :close-on-click-modal="false"
               :visible.sync="dialogVisible">
      <el-table :data="dataList"
                style="width: 100%">
        <el-table-column prop="id"
                         label="序号"
                         width="60"> </el-table-column>
        <el-table-column prop="name"
                         label="姓名"
                         width="100">
        </el-table-column>
        <el-table-column prop="idcard"
                         label="身份证号"
                         width="180">
        </el-table-column>
        <el-table-column prop="telphone"
                         label="手机"></el-table-column>
        <el-table-column fixed="right"
                         header-align="center"
                         align="center"
                         width="150"
                         label="操作">
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       @click="selectMember(scope.row.id)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import IDValidator from 'id-validator'
import GB2260 from 'id-validator/src/GB2260'
import singleUpload from '@/components/upload/singleUpload'

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    singleUpload
  },
  data () {
    // 校验身份证号码合法性
    // eslint-disable-next-line no-unused-vars
    var validIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('身份证号不能为空'))
      }
      var idValidator = new IDValidator(GB2260)
      // console.log(idValidator.isValid(value))
      if (idValidator.isValid(value)) {
        // 查询该身份证是否已被使用
        // this.checkIdCard()
        callback()
      } else {
        callback(new Error('无效身份证号码'))
      }
    }
    var validPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('联系电话不能为空'))
      }
      let reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('无效联系电话'))
      }
    }
    // var validDistrict = (rule, value, callback) => {
    //   if (!value.length) {
    //     return callback(new Error('地区不能为空'))
    //   }
    //   callback()
    // }
    // 这里存放数据
    return {
      idcardVisible: false,
      dialogVisible: false,
      idcardValidMsg: '无效身份证号码',
      idcardDisabled: false,
      avatarUrl: '',
      // value: [],
      districts: [],  // 地区源数据数组
      // 级连下拉框可选项设置
      districtProps: {
        label: 'name',  // 显示的值
        value: 'code',  // 选择的值
        children: 'children'  // 子节点
      },

      // 中华人民共和国行政区划数据
      china: {
        province: [], // 省份
        city: [], // 城市
        area: [] // 区县
      },
      selectOps: {
        sex: [
          { id: 1, name: '男' },
          { id: 0, name: '女' }
        ],
        // 学历
        education: [
          { id: 1, name: '文盲' },
          { id: 2, name: '小学' },
          { id: 3, name: '初中' },
          { id: 4, name: '高中/技校/中专' },
          { id: 5, name: '大学专科以上' },
          { id: 6, name: '不详' }
        ],
        // 有无保险
        insurance: [
          { id: 1, name: '有' },
          { id: 0, name: '无' }
        ],
        // 婚姻状况
        marriage: [
          { id: 1, name: '未婚' },
          { id: 2, name: '已婚' },
          { id: 3, name: '丧偶' },
          { id: 4, name: '离婚' },
          { id: 5, name: '未知' }
        ],
        // 居住情况
        reside: [
          { id: 1, name: '独居' },
          { id: 2, name: '与子女居住' },
          { id: 3, name: '夫妻同居' },
          { id: 4, name: '不详' }
        ],
        // 籍贯
        hometown: [
          { id: 1, name: '汉族' },
          { id: 2, name: '少数民族' }
        ]
      },
      dataList: [],
      dataForm: {
        id: 0,
        name: '',
        age: '',
        sex: '1',
        avatar: '',
        telphone: '',
        idcard: '',
        birthday: '',
        address: '',
        hometown: '',
        hometownVal: '',
        job: '',
        education: '',
        insurance: '',
        hobby: '',
        health: '',
        marriage: '',
        reside: '',
        provincecode: '',
        provincename: '',
        citycode: '',
        cityname: '',
        areacode: '',
        areaname: '',
        districtArr: []
      },
      dataRule: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        age: [{ required: false, message: '年龄不能为空', trigger: 'blur' }],
        sex: [{ required: false, message: '性别不能为空', trigger: 'change' }],
        avatar: [{ required: false, message: '头像不能为空', trigger: 'blur' }],
        telphone: [
          // { required: true, message: '联系电话不能为空', trigger: 'blur' }
          { required: false, validator: validPhone, trigger: 'blur' }
        ],
        idcard: [
          // { required: true, message: '身份证号不能为空', trigger: 'blur' },
          // { required: true, trigger: 'blur' },
          { required: false, validator: validIdCard, trigger: 'blur' }
        ],
        birthday: [
          { required: false, message: '出生日期不能为空', trigger: 'blur' }
        ],
        address: [
          { required: false, message: '居住地址不能为空', trigger: 'blur' }
        ],
        hometown: [
          { required: false, message: '籍贯不能为空', trigger: 'change' }
        ],
        job: [{ required: false, message: '职业不能为空', trigger: 'blur' }],
        education: [
          { required: false, message: '学历不能为空', trigger: 'change' }
        ],
        insurance: [
          { required: false, message: '有无保险不能为空', trigger: 'change' }
        ],
        hobby: [
          { required: false, message: '兴趣爱好不能为空', trigger: 'blur' }
        ],
        health: [
          { required: false, message: '健康状况不能为空', trigger: 'blur' }
        ],
        marriage: [
          { required: false, message: '婚姻状况不能为空', trigger: 'change' }
        ],
        reside: [
          { required: false, message: '居住情况不能为空', trigger: 'change' }
        ],
        districtArr: [
          // { required: true, message: '地区不能为空', trigger: 'change' }
          // { type: 'array', required: true, validator: validDistrict, trigger: 'change' }
          { type: 'array', required: false, message: '地区不能为空', trigger: 'change' }
        ]
        // provincecode: [
        //   { required: true, message: '省份编码不能为空', trigger: 'change' }
        // ],
        // citycode: [
        //   { required: true, message: '城市编码不能为空', trigger: 'change' }
        // ],
        // areacode: [
        //   { required: true, message: '区域编码不能为空', trigger: 'change' }
        // ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    'dataForm.avatar' (newVal, oldVal) {
      if (newVal) {
        let spl = newVal.split('/')
        if (spl.length > 2) {
          this.avatarUrl = spl[spl.length - 2] + '/' + spl[spl.length - 1]
        }
      }
      // console.log(`avatar.new:${newVal}, avatar.old:${oldVal}`)
    }
  },
  // 方法集合
  methods: {
    // 设置step显示的index
    setStepVal () {
      this.$emit('setStepVal', 1)
    },
    // 设置上传后头像地址
    setAvatarUrl (val) {
      this.avatarUrl = val
    },
    // 不足指定位数，后面补零
    pad (num, n) {
      var tbl = []
      var len = n - num.toString().length
      if (len <= 0) return num
      if (!tbl[len]) tbl[len] = (new Array(len + 1)).join('0')
      return num + tbl[len]
    },
    // 地区级连发生改变时调用
    handleChange (value) {
      // console.log(this.dataForm.districtArr)
      // 效果：项目名称的input框随着内容的长度而自适应，设置 el_cascader 标签的width
      // var elCascader = document.querySelector('#el-cascader')
      // var length = value.join('/').length + 1
      // var num = length * 13 + 'px'
      // elCascader.style.width = num
    },
    // 获取地区数据
    getDistricts () {
      this.$http({
        url: this.$http.adornUrl(`/member/cnprovince/districts`),
        method: 'get'
      }).then(({ data }) => {
        if (data.code === 0) {
          this.districts = data.data.districts
        }
      })
    },
    // 获取省份数据
    getProvince () {
      this.$http({
        url: this.$http.adornUrl(`/member/cnprovince/list`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.china.province = data.page.list
        }
      })
    },
    // 获取城市数据
    getCity (code, target = 1) {
      this.dataForm.provincename = this.china.province.find((item) => {
        return item.code === code
      }).name
      if (target === 1) {
        this.dataForm.citycode = ''
        this.china.city = []

        this.dataForm.areacode = ''
        this.china.area = []
      }

      this.$http({
        url: this.$http.adornUrl(`/member/cncity/province/${code}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.china.city = data.data
          // console.log(this.china.city)
        }
      })
    },
    // 获取区域数据
    getArea (code, target = 1) {
      this.dataForm.cityname = this.china.city.find((item) => {
        return item.code === code
      }).name
      if (target === 1) {
        this.dataForm.areacode = ''
        this.china.area = []
      }
      this.$http({
        url: this.$http.adornUrl(`/member/cnarea/city/${code}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.china.area = data.data
        }
      })
    },
    // 获取区域数据
    areaChange (code) {
      this.dataForm.areaname = this.china.area.find((item) => {
        return item.code === code
      }).name
    },
    // 检查身份证号是否已使用
    checkIdCard () {
      this.$http({
        url: this.$http.adornUrl(
          `/member/member/select/idcard/${this.dataForm.idcard}`
        ),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.data) {
            // console.log(data.data)
            if (data.data.length === 0) {
              for (var item in this.dataForm) {
                if (item === 'idcard') {
                  continue
                }
                this.dataForm[item] = null
              }
            } else if (data.data.length === 1) {
              // 查询出来只有一条记录
              this.$confirm('身份证号已存在, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  this.$message({
                    type: 'success',
                    message: '查询基础资料'
                  })
                })
                .catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消操作'
                  })
                })
            } else {
              // 查询出来有多条记录
              this.dataList = data.data
              this.dialogVisible = true
            }
          }
        }
      })
    },

    // 选择的基础资料
    selectMember (id) {
      for (let i = 0; i < this.dataList.length; i++) {
        const elem = this.dataList[i]
        if (elem['id'] === id) {
          let data = this.dataList[i]
          this.dataForm.id = data.id
          this.dataForm.name = data.name
          this.dataForm.age = data.age
          this.dataForm.sex = data.sex
          this.dataForm.avatar = data.avatar
          this.dataForm.telphone = data.telphone
          this.dataForm.idcard = data.idcard
          this.dataForm.birthday = data.birthday
          this.dataForm.address = data.address
          this.dataForm.hometown = data.hometown
          this.dataForm.job = data.job
          this.dataForm.education = data.education
          this.dataForm.insurance = data.insurance
          this.dataForm.hobby = data.hobby
          this.dataForm.health = data.health
          this.dataForm.marriage = data.marriage
          this.dataForm.reside = data.reside
          this.dataForm.provicecode = data.provicecode
          this.dataForm.citycode = data.citycode
          this.dataForm.areacode = data.areacode
          break
        }
      }
      if (this.dataForm.provicecode) {
        this.getCity(this.dataForm.provicecode, 0)
      }
      if (this.dataForm.citycode) {
        this.getArea(this.dataForm.citycode, 0)
      }
      this.dialogVisible = false
      this.dataList = []
    },

    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/member/member/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              age: this.dataForm.age,
              sex: this.dataForm.sex,
              avatar: this.avatarUrl || this.dataForm.avatar,
              telphone: this.dataForm.telphone,
              idcard: this.dataForm.idcard,
              birthday: this.dataForm.birthday ? this.dataForm.birthday.getTime() / 1000 : '',
              address: this.dataForm.address,
              hometownVal: this.dataForm.hometownVal,
              job: this.dataForm.job,
              education: this.dataForm.education,
              insurance: this.dataForm.insurance,
              hobby: this.dataForm.hobby,
              health: this.dataForm.health,
              marriage: this.dataForm.marriage,
              reside: this.dataForm.reside,
              provincecode: this.dataForm.districtArr.length === 3 ? this.pad(this.dataForm.districtArr[0], 6) : '',
              citycode: this.dataForm.districtArr.length === 3 ? this.pad(this.dataForm.districtArr[1], 6) : '',
              areacode: this.dataForm.districtArr.length === 3 ? this.pad(this.dataForm.districtArr[2], 6) : '',
              // provincecode: this.dataForm.provincecode,
              provincename: this.dataForm.provincename,
              // citycode: this.dataForm.citycode,
              cityname: this.dataForm.cityname,
              // areacode: this.dataForm.areacode,
              areaname: this.dataForm.areaname,
              createdBy: this.$store.state.user.name
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              // 清空所有字段值
              this.resetFieldsVal()
              // this.china.city = []
              // this.china.area = []
              // this.china.province = []
              // this.getProvince()
              // 重置表单
              this.$refs['dataForm'].resetFields()
              // 设置激活步骤
              this.$emit('setStepVal', 1)
              // 操作成功提示
              this.$message({
                message: '基础资料录入成功',
                type: 'success',
                duration: 1500
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    resetFieldsVal () {
      for (var item in this.dataForm) {
        if (item === 'districtArr') {
          this.dataForm[item] = []
        } else {
          this.dataForm[item] = ''
        }
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // this.getProvince()
    this.getDistricts()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
.el-radio-group {
  display: block;
}
/* .el-cascader-panel {
  height: 200px;
} */
/* .el-cascader-panel .el-scrollbar__wrap {
  max-height: 300px;
  min-height: 100px;
  overflow-x: hidden;
} */
</style>